import router from "@/routes";
import { LocalStorage, CookiesStorage, SessionStorage } from "@/utils/storage";
import { defineStore } from "pinia";
import { useRouteStore } from "./routes";
import { clearAllRegisteredRouter } from "@/utils/registerRouter";
import { defaultLanguage } from "@/views/login/store";
import { LoginRouteComponent } from "@/routes/basics.router";
import { getLanguage } from "@/lang/tools";
import { closeChildWindow } from "@/utils/childWindow";

export const useUserStore = defineStore("user", {
  state: () => ({
    token: "",
    userinfo: {} as any,
    rememberPsd: false,
    username: "",
    password: "",
  }),
  getters: {},
  actions: {
    setUserinfo(user: any) {
      this.userinfo = user;
    },
    setToken(token: any) {
      this.token = token;
    },
    setRememberPsd(rememberPsd: any) {
      this.rememberPsd = rememberPsd;
    },
    setUsername(username: any) {
      this.username = username;
    },
    setPassword(password: any) {
      this.password = password;
    },
    logout() {
      const routeStore = useRouteStore();
      defaultLanguage.value = getLanguage();
      this.setUserinfo({}); // 清除用户信息
      clearAllRegisteredRouter(); // 重置路由注册状态
      this.setToken("");
      routeStore.setRoutes([]); // 清除菜单数据
      routeStore.setPowers([]); // 清除权限数据
      closeChildWindow(); // 关闭子窗口
      router?.replace(LoginRouteComponent.path);
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        storage: LocalStorage,
        paths: ["rememberPsd", "username", "password", "userinfo"],
      },
      { storage: CookiesStorage, paths: ["token"] },
      {
        storage: SessionStorage,
        paths: [],
      },
    ],
  },
});
